import dayjs from "dayjs";

/**
 * 获取token
 * @returns {undefined}
 */
export function getToken() {
    const token = localStorage.getItem('token');
    const tokenExpires = Number(localStorage.getItem('token-expires') || 0);

    if (!token || !tokenExpires) return undefined;

    const now = dayjs();

    if (now.isBefore(dayjs(tokenExpires))) {
        // token 还有效
        return token;
    }

    return undefined;
}

/**
 * 在扩展插件中, cookie被插件隔离, 保存不上, 所以还是用localStorage保存吧
 * 并通过expirationDate保存token剩余有效秒数
 * @param {*} payload token
 * @param {*} time 有效时间(小时数)
 */
export function setToken(payload: any, time = 8) {
    // 保存毫秒
    const expirationDate = dayjs().add(Number(time), "hour").valueOf();
    localStorage.setItem("token", payload)
    localStorage.setItem("token-expires", expirationDate + "")
    localStorage.setItem("token-expires-format", dayjs(expirationDate).format("YYYY-MM-DD HH:mm:ss"))
}

/**
 * 移除token
 */
export function clearToken() {
    localStorage.removeItem("token");
    localStorage.removeItem("token-expires");
    localStorage.removeItem("token-expires-format");
}
